package client

import (
	"context"
	ps "github.com/zhongshaofa/swan-jobs/internal/rpc/proto/scheduler"
	"google.golang.org/grpc"
	"log"
	"time"
)

func StartTaskByClient(connectAddress string, request *ps.TaskRequest) (*ps.TaskResponse, error) {
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second*2)
	defer cancel()

	conn, err := grpc.DialContext(ctx, connectAddress, grpc.WithBlock(), grpc.WithInsecure())
	if err != nil {
		log.Println("did not connect:", err)
		return nil, err
	}

	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)

	rpcServer := ps.NewServiceClient(conn)
	result, err := rpcServer.StartTask(ctx, request)

	return result, err
}

func ReloadTaskByClient(connectAddress string, request *ps.TaskRequest) (*ps.TaskResponse, error) {
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second*2)
	defer cancel()

	conn, err := grpc.DialContext(ctx, connectAddress, grpc.WithBlock(), grpc.WithInsecure())
	if err != nil {
		log.Println("did not connect:", err)
		return nil, err
	}

	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)

	rpcServer := ps.NewServiceClient(conn)
	result, err := rpcServer.ReloadTask(ctx, request)

	return result, err
}

func StopTaskByClient(connectAddress string, request *ps.TaskRequest) (*ps.TaskResponse, error) {
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second*2)
	defer cancel()

	conn, err := grpc.DialContext(ctx, connectAddress, grpc.WithBlock(), grpc.WithInsecure())
	if err != nil {
		log.Println("did not connect:", err)
		return nil, err
	}

	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)

	rpcServer := ps.NewServiceClient(conn)
	result, err := rpcServer.StopTask(ctx, request)

	return result, err
}

func OneKeyReloadSupervisorByClient(connectAddress string, request *ps.TaskRequest) (*ps.TaskResponse, error) {
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second*2)
	defer cancel()

	conn, err := grpc.DialContext(ctx, connectAddress, grpc.WithBlock(), grpc.WithInsecure())
	if err != nil {
		log.Println("did not connect:", err)
		return nil, err
	}

	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)

	rpcServer := ps.NewServiceClient(conn)
	result, err := rpcServer.OneKeyReloadSupervisor(ctx, request)

	return result, err
}
